﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GS.Cricket.Web
{
    public partial class Team : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["validuser"] != null)
            {
                if (!(Boolean)Session["validuser"])
                {
                    Panel_GroupAdmin.Visible = false;
                    Panel_TeamAdmin.Visible = false;
                    Panel_PlayerAdmin.Visible = false;
                }
            }
            else
            {

                Panel_GroupAdmin.Visible = false;
                Panel_TeamAdmin.Visible = false;
                Panel_PlayerAdmin.Visible = false;
            }

            GroupGridBind();
            TeamGridBind();
            PlayerGridBind();
        }



        protected void TeamGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            PlayerGridBind();
        }

        protected void GroupGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            TeamGrid.SelectedIndex = -1;
            TeamGridBind();
            PlayerGridBind();
        }


        #region Important! Select Row Capability
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            AddRowSelectToGridView(GroupGrid);
            AddRowSelectToGridView(TeamGrid);
            AddRowSelectToGridView(PlayerGrid);
            base.Render(writer);
        }

        private void AddRowSelectToGridView(GridView gv)
        {
            foreach (GridViewRow row in gv.Rows)
            {
                row.Attributes["onmouseover"] = "this.style.cursor='pointer'";
                row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gv, "Select$" + row.RowIndex.ToString(), true));
            }
        }
        #endregion


        protected void Button_AddTeamClick(object sender, EventArgs e)
        {
            string teamName = TextBox_AddTeam.Text.Trim();

            if (teamName.Equals(String.Empty))
            {
                Label_TeamError.Text = "Please enter a team name.";
            }
            else
            {
                var teamService = new GS.Cricket.Service.Impl.TeamService();
                var teams = teamService.GetAll().ToList();
                var duplicateTeam = teams.Any(t => t.Name.Equals(teamName));

                if (duplicateTeam)
                {
                    Label_TeamError.Text = "Team \"" + teamName + "\" already exist.";
                }
                else
                {
                    var id = -1;
                    if (GroupGrid.SelectedIndex != -1)
                    {
                        id = Convert.ToInt32(GroupGrid.DataKeys[GroupGrid.SelectedRow.RowIndex].Value);
                    }

                    var newTeam = new GS.Cricket.Entities.Team()
                    {
                        Name = teamName
                    };

                    if (id > -1)
                    {
                        newTeam.Group = id;
                    }

                    if (teamService.Add(newTeam) > -1)
                    {
                        TeamGridBind();
                    }
                }
            }
        }

        protected void Button_AddPlayerClick(object sender, EventArgs e)
        {
            string playerName = TextBox_AddPlayer.Text.Trim();

            if (playerName.Equals(String.Empty))
            {
                Label_PlayerError.Text = "Please enter the player name.";
            }
            else
            {
                var playerService = new GS.Cricket.Service.Impl.PlayerService();
                var players = playerService.GetAllPlayers().ToList();
                var duplicatePlayer = players.Any(p => p.Name.Equals(playerName));

                if (duplicatePlayer)
                {
                    Label_PlayerError.Text = "Player \"" + playerName + "\" already exist.";
                }
                else
                {
                    if (TeamGrid.SelectedIndex <= 0)
                    {
                        Label_PlayerError.Text = "Please select a valid team first.";
                    }
                    else
                    {
                        int teamId = Convert.ToInt32(TeamGrid.DataKeys[TeamGrid.SelectedRow.RowIndex].Value);

                        var newPlayer = new GS.Cricket.Entities.Player()
                        {
                            Name = playerName,
                            TeamId = teamId
                        };
                        if (playerService.Add(newPlayer) > -1)
                        {
                            PlayerGridBind();
                        }
                    }
                }
            }
        }

        protected void Button_AddGroupClick(object sender, EventArgs e)
        {
            string groupName = TextBox_AddGroup.Text.Trim();

            if (groupName.Equals(String.Empty))
            {
                Label_GroupError.Text = "Please enter a group name.";
            }
            else
            {
                var groupService = new GS.Cricket.Service.Impl.GroupService();
                var groups = groupService.GetAll().ToList();
                var duplicateGroup = groups.Any(t => t.Name.Equals(groupName));

                if (duplicateGroup)
                {
                    Label_GroupError.Text = "Group \"" + groupName + "\" already exist.";
                }
                else
                {
                    var newGroup = new GS.Cricket.Entities.Group()
                    {
                        Name = groupName
                    };
                    if (groupService.Add(newGroup) > -1)
                    {
                        GroupGridBind();
                        TeamGridBind();
                        PlayerGridBind();
                    }
                }
            }
        }

        protected void Button_DeleteTeamClick(object sender, EventArgs e)
        {
            if (TeamGrid.SelectedIndex > 0)
            {
                int id = Convert.ToInt32(TeamGrid.DataKeys[TeamGrid.SelectedRow.RowIndex].Value);
                var teamService = new GS.Cricket.Service.Impl.TeamService();
                teamService.Delete(id);
                TeamGrid.SelectedIndex = -1;
                TeamGridBind();
                PlayerGridBind();
            }
            else
            {
                Label_TeamError.Text = "Please select a team first.";
            }
        }

        protected void Button_DeletePlayerClick(object sender, EventArgs e)
        {
            if (PlayerGrid.SelectedIndex > -1)
            {
                int id = Convert.ToInt32(PlayerGrid.DataKeys[PlayerGrid.SelectedRow.RowIndex].Value);
                var playerService = new GS.Cricket.Service.Impl.PlayerService();
                PlayerGrid.SelectedIndex = -1;
                playerService.Delete(id);
                PlayerGridBind();
            }
            else
            {
                Label_PlayerError.Text = "Please select a player first.";
            }
        }

        protected void Button_DeleteGroupClick(object sender, EventArgs e)
        {
            if (GroupGrid.SelectedIndex > 0)
            {
                int id = Convert.ToInt32(GroupGrid.DataKeys[GroupGrid.SelectedRow.RowIndex].Value);
                var groupService = new GS.Cricket.Service.Impl.GroupService();
                groupService.Delete(id);
                GroupGrid.SelectedIndex = -1;
                TeamGrid.SelectedIndex = -1;
                GroupGridBind();
                TeamGridBind();
                PlayerGridBind();
            }
            else
            {
                Label_GroupError.Text = "Please select a group first.";
            }
        }

        protected void Button_RenameGroupClick(object sender, EventArgs e)
        {
            var groupId = Int32.Parse(GroupGrid.SelectedValue.ToString());
            var newName = TextBox_AddGroup.Text.Trim();
            if (groupId == 0)
            {
                Label_GroupError.Text = "Please select a group first.";
            }
            else
            {
                if (newName.Length.Equals(0))
                {
                    Label_GroupError.Text = "Enter a new group name first.";
                }
                else
                {
                    var groupService = new GS.Cricket.Service.Impl.GroupService();
                    var groups = groupService.GetAll().ToList();
                    var duplicateGroup = groups.Any(g => g.Name.Equals(newName));
                    if (duplicateGroup)
                    {
                        Label_GroupError.Text = "Group \"" + newName + "\" already exist";
                    }
                    else
                    {
                        var group = groupService.GetById(groupId);
                        group.Name = newName;
                        groupService.Update(group);
                        GroupGridBind();
                    }
                }
            }

        }

        protected void Button_RenameTeamClick(object sender, EventArgs e)
        {
            var teamId = Int32.Parse(TeamGrid.SelectedValue.ToString());
            var newName = TextBox_AddTeam.Text.Trim();
            if (teamId == 0)
            {
                Label_TeamError.Text = "Please select a team first.";
            }
            else
            {
                if (newName.Length.Equals(0))
                {
                    Label_TeamError.Text = "Enter a new team name first.";
                }
                else
                {
                    var teamService = new GS.Cricket.Service.Impl.TeamService();
                    var teams = teamService.GetAll().ToList();
                    var duplicateTeam = teams.Any(t => t.Name.Equals(newName));
                    if (duplicateTeam)
                    {
                        Label_TeamError.Text = "Team \"" + newName + "\" already exist";
                    }
                    else
                    {
                        var team = teamService.GetById(teamId);
                        team.Name = newName;
                        teamService.Update(team);
                        TeamGridBind();
                    }
                }
            }
        }

        protected void Button_RenamePlayerClick(object sender, EventArgs e)
        {
            var playerId = Int32.Parse(PlayerGrid.SelectedValue.ToString());
            var newName = TextBox_AddPlayer.Text.Trim();
            if (playerId == 0)
            {
                Label_PlayerError.Text = "Please select a player first.";
            }
            else
            {
                if (newName.Length.Equals(0))
                {
                    Label_PlayerError.Text = "Enter a new player name first.";
                }
                else
                {
                    var playerService = new GS.Cricket.Service.Impl.PlayerService();
                    var players = playerService.GetAllPlayers().ToList();
                    var duplicatePlayer = players.Any(p => p.Name.Equals(newName));
                    if (duplicatePlayer)
                    {
                        Label_PlayerError.Text = "Player \"" + newName + "\" already exist.";
                    }
                    else
                    {
                        var player = playerService.GetById(playerId);
                        player.Name = newName;
                        playerService.Update(player);
                        PlayerGridBind();
                    }
                }
            }
        }

        protected void Button_AddToGroup(object sender, CommandEventArgs e)
        {
            var groupId = Int32.Parse(e.CommandArgument.ToString());
            if (TeamGrid.SelectedIndex == -1)
            {
                Label_TeamError.Text = "Please select a team first.";
            }
            else
            {
                var teamId = Int32.Parse(TeamGrid.SelectedValue.ToString());
                if (teamId == 0)
                {
                    Label_TeamError.Text = "Please select a valid team.";
                }
                else
                {
                    var teamService = new GS.Cricket.Service.Impl.TeamService();
                    var team = teamService.GetById(teamId);
                    if (team.Group != groupId)
                    {
                        team.Group = groupId;
                        teamService.Update(team);
                        TeamGrid.SelectedIndex = -1;
                        GroupGridBind();
                        TeamGridBind();
                    }
                }
            }
        }

        protected void Button_AddToTeam(object sender, CommandEventArgs e)
        {
            var teamId = Int32.Parse(e.CommandArgument.ToString());
            if (PlayerGrid.SelectedIndex == -1)
            {
                Label_PlayerError.Text = "Please select a player first.";
            }
            else
            {
                var playerId = Int32.Parse(PlayerGrid.SelectedValue.ToString());
                if (playerId == 0)
                {
                    Label_PlayerError.Text = "Please select a valid player.";
                }
                else
                {
                    var playerService = new GS.Cricket.Service.Impl.PlayerService();
                    var player = playerService.GetById(playerId);
                    if (player.TeamId != teamId)
                    {
                        player.TeamId = teamId;
                        playerService.Update(player);
                        PlayerGrid.SelectedIndex = -1;
                        GroupGridBind();
                        TeamGridBind();
                        PlayerGridBind();
                    }
                }
            }
        }

        private void TeamGridBind()
        {
            var id = -1;
            if (GroupGrid.SelectedIndex != -1)
            {
                id = Convert.ToInt32(GroupGrid.DataKeys[GroupGrid.SelectedRow.RowIndex].Value);
            }
            var teamService = new GS.Cricket.Service.Impl.TeamService();
            var teams = teamService.GetAll().ToList();

            if (id > 0)
            {
                teams = teams.Where(team => team.Group.Equals(id)).ToList();
            }

            var allLink = new GS.Cricket.Entities.Team()
            {
                Name = "All",
                Id = 0
            };
            teams.Insert(0, allLink);

            TeamGrid.DataSource = teams.Select(team => team);
            TeamGrid.AutoGenerateColumns = false;
            TeamGrid.DataBind();

            Label_TeamError.Text = String.Empty;
            Label_TeamSuccess.Text = String.Empty;

            Repeater_Team.DataSource = teams.Select(Team => Team).Skip(1);
            Repeater_Team.DataMember = "Name";
            Repeater_Team.DataBind();
        }

        private void PlayerGridBind()
        {
            var id = -1;
            if (TeamGrid.SelectedIndex != -1)
            {
                id = Convert.ToInt32(TeamGrid.DataKeys[TeamGrid.SelectedRow.RowIndex].Value);
            }
            var playerService = new GS.Cricket.Service.Impl.PlayerService();
            var players = playerService.GetAllPlayers().ToList();

            if (id > 0)
            {
                players = players.Where(player => player.TeamId.Equals(id)).ToList();
            }

            PlayerGrid.DataSource = players.Select(player => player);
            PlayerGrid.AutoGenerateColumns = false;
            PlayerGrid.DataBind();

            Label_PlayerError.Text = String.Empty;
            Label_PlayerSuccess.Text = String.Empty;
        }

        private void GroupGridBind()
        {
            var groupService = new GS.Cricket.Service.Impl.GroupService();
            var groups = groupService.GetAll().ToList();

            var allLink = new GS.Cricket.Entities.Group()
            {
                Name = "All",
                Id = 0
            };
            groups.Insert(0, allLink);

            GroupGrid.DataSource = groups.Select(group => group);
            GroupGrid.AutoGenerateColumns = false;
            GroupGrid.DataBind();

            Label_GroupError.Text = String.Empty;
            Label_GroupSuccess.Text = String.Empty;

            Repeater_Group.DataSource = groups.Select(group => group);
            Repeater_Group.DataMember = "Name";
            Repeater_Group.DataBind();
        }

    }
}